package com.spreedairy.item;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import com.liferay.compat.portal.util.PortalUtil;
import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.dao.orm.DynamicQuery;
import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.Constants;

import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.security.auth.PrincipalException;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portlet.asset.NoSuchCategoryException;
import com.liferay.portlet.shopping.DuplicateItemSKUException;
import com.liferay.portlet.shopping.ItemLargeImageNameException;
import com.liferay.portlet.shopping.ItemLargeImageSizeException;
import com.liferay.portlet.shopping.ItemMediumImageNameException;
import com.liferay.portlet.shopping.ItemMediumImageSizeException;
import com.liferay.portlet.shopping.ItemNameException;
import com.liferay.portlet.shopping.ItemSKUException;
import com.liferay.portlet.shopping.ItemSmallImageNameException;
import com.liferay.portlet.shopping.ItemSmallImageSizeException;
import com.liferay.portlet.shopping.NoSuchItemException;
import com.liferay.portlet.shopping.model.ShoppingCart;
import com.liferay.portlet.shopping.model.ShoppingItem;
import com.liferay.portlet.shopping.model.ShoppingItemField;
import com.liferay.portlet.shopping.model.ShoppingItemPrice;
import com.liferay.portlet.shopping.model.ShoppingItemPriceConstants;
import com.liferay.portlet.shopping.model.ShoppingOrder;
import com.liferay.portlet.shopping.service.ShoppingCartLocalServiceUtil;
import com.liferay.portlet.shopping.service.ShoppingItemLocalServiceUtil;
import com.liferay.portlet.shopping.service.ShoppingItemServiceUtil;
import com.liferay.portlet.shopping.service.ShoppingOrderLocalServiceUtil;
import com.liferay.portlet.shopping.service.persistence.ShoppingItemFieldUtil;
import com.liferay.portlet.shopping.service.persistence.ShoppingItemPriceUtil;
import com.spreedairy.common.CommonAction;
import com.spreedairy.portal.NoSuchCustomFieldException;
import com.spreedairy.portal.model.CustomField;
import com.spreedairy.portal.model.CustomFieldValue;
import com.spreedairy.portal.model.impl.CustomFieldValueImpl;
import com.spreedairy.portal.service.CustomFieldLocalServiceUtil;
import com.spreedairy.portal.service.CustomFieldValueLocalServiceUtil;
import com.spreedairy.util.ProductUtil;

public class ItemPortlet extends CommonAction {

	public void doView(RenderRequest renderRequest,
			RenderResponse renderResponse) throws IOException, PortletException {
		try {
			getItem(renderRequest, renderResponse);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		super.doView(renderRequest, renderResponse);
	}
	
	public void userWishItem(ActionRequest actionRequest,
			ActionResponse actionResponse) throws IOException, PortletException {
		addUserWish(actionRequest, actionResponse);
	}

	private void getItem(RenderRequest renderRequest,
			RenderResponse renderResponse) throws NumberFormatException, PortalException, SystemException {
		String itemId = (String) renderRequest.getParameter("itemId");
		String cmd = (String) renderRequest.getParameter(Constants.CMD);
				
				if (Validator.isNotNull(cmd) && (cmd.equals("defineField") )) {
			long categoryId = ParamUtil.getLong(renderRequest, "categoryId");
			
			if(categoryId==0) {
				renderRequest.setAttribute("DEFINE_FIELD_LIST", null);
			} 
			else {
				List<CustomField> list = null;
				try {
					list = CustomFieldLocalServiceUtil.findByCategoryId(categoryId);
				} catch (NoSuchCustomFieldException e) {
					e.printStackTrace();
				} catch (SystemException e) {
					e.printStackTrace();
				}
				renderRequest.setAttribute("DEFINE_FIELD_LIST", list);
			}
			viewTemplate  = "/html/item/edit_item.jsp";
		} else {
			ShoppingItem item = null;
			try {
				if (Long.parseLong(itemId) > 0) {
					item = com.liferay.portlet.shopping.service.ShoppingItemServiceUtil
							.getItem(Long.parseLong(itemId));
				}
				
			} catch (Exception e) {
			}
			
			if(Validator.isNotNull(cmd) && (cmd.equals("edit") || cmd.equals("add"))) {
				if(cmd.equals("edit")){
				//long categoryId = ParamUtil.getLong(renderRequest, "categoryId");
				String itemIdd = (String) renderRequest.getParameter("itemId");
				ShoppingItem itemm=ShoppingItemLocalServiceUtil.getItem(Long.parseLong(itemIdd));
				List<CustomField> list = null;
				try {
					list = CustomFieldLocalServiceUtil.findByCategoryId(itemm.getCategoryId());
				} catch (NoSuchCustomFieldException e) {
					e.printStackTrace();
				} catch (SystemException e) {
					e.printStackTrace();
				}
				renderRequest.setAttribute("DEFINE_FIELD_LIST", list);
				viewTemplate = "/html/item/edit_item.jsp";
				
				}
			} else {
				viewTemplate = "/html/item/item_list.jsp";
			}
			
			renderRequest.setAttribute("SHOPPING_ITEM", item);
		}
		
	}

	public void addProcess(ActionRequest actionRequest,
			ActionResponse actionResponse) throws Exception {
		
		String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
		
		try {
			if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
				updateItem(actionRequest);
				
			} else if (cmd.equals(Constants.DELETE)) {
				deleteItem(actionRequest);
				
			}  
			else if (cmd.equals(Constants.SEARCH)) {
				searchItem(actionRequest,actionResponse);
				
			}  
			if (Validator.isNotNull(cmd)) {
				sendRedirect(actionRequest, actionResponse);
			}
		} catch (Exception e) {
			if (e instanceof NoSuchCategoryException
					|| e instanceof NoSuchItemException
					|| e instanceof PrincipalException) {

				SessionErrors.add(actionRequest, e.getClass().getName());

				// setForward(actionRequest, "portlet.shopping.error");
			} else if (e instanceof DuplicateItemSKUException
					|| e instanceof ItemLargeImageNameException
					|| e instanceof ItemLargeImageSizeException
					|| e instanceof ItemMediumImageNameException
					|| e instanceof ItemMediumImageSizeException
					|| e instanceof ItemNameException
					|| e instanceof ItemSKUException
					|| e instanceof ItemSmallImageNameException
					|| e instanceof ItemSmallImageSizeException) {

				SessionErrors.add(actionRequest, e.getClass().getName());
			} else {
				throw e;
			}
		}
	}

	private void searchItem(ActionRequest actionRequest,
			ActionResponse actionResponse) {
		// TODO Auto-generated method stub
		String searchData = ParamUtil.getString(actionRequest, "searchData");
		try	{
			DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(ShoppingItem.class,PortalClassLoaderUtil.getClassLoader());
		    if(Validator.isNotNull(searchData)) dynamicQuery.add(RestrictionsFactoryUtil.like("name","%"+searchData+"%"));
		    List<ShoppingOrder> searchItemList = ShoppingOrderLocalServiceUtil.dynamicQuery(dynamicQuery);
			PortletSession session=actionRequest.getPortletSession();
			session.setAttribute("SEARCH_ITEMLIST", searchItemList);
			
			}catch(Exception ee){
				System.out.println("Exception"+ee);
			}
	}

	/*
	 * public ActionForward render( ActionMapping mapping, ActionForm form,
	 * PortletConfig portletConfig, RenderRequest renderRequest, RenderResponse
	 * renderResponse) throws Exception {
	 * 
	 * try { ActionUtil.getItem(renderRequest); } catch (Exception e) { if (e
	 * instanceof NoSuchItemException || e instanceof PrincipalException) {
	 * 
	 * SessionErrors.add(renderRequest, e.getClass().getName());
	 * 
	 * return mapping.findForward("portlet.shopping.error"); } else { throw e; }
	 * }
	 * 
	 * return mapping.findForward( getForward(renderRequest,
	 * "portlet.shopping.edit_item")); }
	 */

	protected void deleteItem(ActionRequest actionRequest) throws Exception {
		long itemId = ParamUtil.getLong(actionRequest, "itemId");

		
		ShoppingItemServiceUtil.deleteItem(itemId);
		
	}
	protected void updateItem(ActionRequest actionRequest) throws Exception {
		UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
		//System.out.println("EDIT");

		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest
				.getAttribute(WebKeys.THEME_DISPLAY);

		long itemId = ParamUtil.getLong(uploadRequest, "itemId");

		long groupId = themeDisplay.getScopeGroupId();
		long categoryId = ParamUtil.getLong(uploadRequest, "categoryId");
		String sku = ParamUtil.getString(uploadRequest, "sku");
		String name = ParamUtil.getString(uploadRequest, "name");
		String description = ParamUtil.getString(uploadRequest, "description");
		String properties = ParamUtil.getString(uploadRequest, "properties");

		int fieldsCount = ParamUtil.getInteger(uploadRequest, "fieldsCount", 1);

		List<ShoppingItemField> itemFields = new ArrayList<ShoppingItemField>();

		for (int i = 0; i < fieldsCount; i++) {
			String fieldName = ParamUtil.getString(uploadRequest, "fieldName"
					+ i);
			String fieldValues = ParamUtil.getString(uploadRequest,
					"fieldValues" + i);
			String fieldDescription = ParamUtil.getString(uploadRequest,
					"fieldDescription" + i);

			ShoppingItemField itemField = ShoppingItemFieldUtil.create(0);

			itemField.setName(fieldName);
			itemField.setValues(fieldValues);
			itemField.setDescription(fieldDescription);

			itemFields.add(itemField);
		}

		String fieldsQuantities = ParamUtil.getString(uploadRequest,
				"fieldsQuantities");

		int pricesCount = ParamUtil.getInteger(uploadRequest, "pricesCount", 1);
        
		List<ShoppingItemPrice> itemPrices = new ArrayList<ShoppingItemPrice>();

		for (int i = 0; i < pricesCount; i++) {
			int minQuantity = ParamUtil.getInteger(uploadRequest, "minQuantity"
					+ i);
			int maxQuantity = ParamUtil.getInteger(uploadRequest, "maxQuantity"
					+ i);
			double price = ParamUtil.getDouble(uploadRequest, "price" + i);
			System.out.println("price"+price);
			double discount = ParamUtil
					.getDouble(uploadRequest, "discount" + i) / 100;
			boolean taxable = ParamUtil
					.getBoolean(uploadRequest, "taxable" + i);
			double shipping = ParamUtil
					.getDouble(uploadRequest, "shipping" + i);
			boolean useShippingFormula = ParamUtil.getBoolean(uploadRequest,
					"useShippingFormula" + i);
			boolean active = ParamUtil.getBoolean(uploadRequest, "active" + i);
			int defaultPrice = ParamUtil.getInteger(uploadRequest,
					"defaultPrice");
            System.out.println("defaultPrice"+defaultPrice);
			int status = ShoppingItemPriceConstants.STATUS_ACTIVE_DEFAULT;

			if ((defaultPrice != i) && active) {
				status = ShoppingItemPriceConstants.STATUS_ACTIVE;
			} else if ((defaultPrice != i) && !active) {
				status = ShoppingItemPriceConstants.STATUS_INACTIVE;
			}

			ShoppingItemPrice itemPrice = ShoppingItemPriceUtil.create(0);

			itemPrice.setMinQuantity(minQuantity);
			itemPrice.setMaxQuantity(maxQuantity);
			itemPrice.setPrice(price);
			itemPrice.setDiscount(discount);
			itemPrice.setTaxable(taxable);
			itemPrice.setShipping(shipping);
			itemPrice.setUseShippingFormula(useShippingFormula);
			itemPrice.setStatus(status);
            
			itemPrices.add(itemPrice);
			
		}

		boolean requiresShipping = ParamUtil.getBoolean(uploadRequest,
				"requiresShipping");
		int stockQuantity = ParamUtil
				.getInteger(uploadRequest, "stockQuantity");

		boolean featured = ParamUtil.getBoolean(uploadRequest, "featured");
		Boolean sale = null;

		boolean smallImage = ParamUtil.getBoolean(uploadRequest, "smallImage");
		String smallImageURL = ParamUtil.getString(uploadRequest,
				"smallImageURL");
		File smallFile = uploadRequest.getFile("smallFile");

		boolean mediumImage = ParamUtil
				.getBoolean(uploadRequest, "mediumImage");
		String mediumImageURL = ParamUtil.getString(uploadRequest,
				"mediumImageURL");
		File mediumFile = uploadRequest.getFile("mediumFile");

		boolean largeImage = ParamUtil.getBoolean(uploadRequest, "largeImage");
		String largeImageURL = ParamUtil.getString(uploadRequest,
				"largeImageURL");
		
		File largeFile = uploadRequest.getFile("largeFile");

		ServiceContext serviceContext = ServiceContextFactory.getInstance(
				ShoppingItem.class.getName(), actionRequest);
		System.out.println("itemId======>>>>>" + itemId);
		if (itemId <= 0) {

			// Add item
			System.out.println("addItem======>>>>>"+sku);
			ShoppingItem shoppingItem = null;
		
			shoppingItem = ShoppingItemServiceUtil.addItem(groupId, categoryId, sku, name,
					description, properties, fieldsQuantities,
					requiresShipping, stockQuantity, featured, sale,
					smallImage, smallImageURL, smallFile, mediumImage,
					mediumImageURL, mediumFile, largeImage, largeImageURL,
					largeFile, itemFields, itemPrices, serviceContext);
			
			System.out.println("itemId ------======>>>>>"+shoppingItem.getItemId());
			List<CustomField> list = (List) CustomFieldLocalServiceUtil.findByCategoryId(categoryId);
			
			for(CustomField field : list) {
				String fieldValue = ParamUtil.getString(uploadRequest, field.getKeyValue());
				CustomFieldValue cfValue = new CustomFieldValueImpl();
				long recId= CounterLocalServiceUtil.increment("CustomFieldValue.class");
				cfValue.setRecId(recId);
				cfValue.setItemId(shoppingItem.getItemId());
				cfValue.setKeyName(field.getKeyValue());
				cfValue.setKeyValue(fieldValue);
				CustomFieldValueLocalServiceUtil.addCustomFieldValue(cfValue);
			}
			System.out.println("custom added..................");
			
		} else {

			ShoppingItem item=ShoppingItemServiceUtil.getItem(itemId);
			ShoppingItemServiceUtil.updateItem(itemId, groupId, categoryId,
					sku, name, description, properties, fieldsQuantities,
					requiresShipping, stockQuantity, featured, sale,
					smallImage, smallImageURL, smallFile, mediumImage,
					mediumImageURL, mediumFile, largeImage, largeImageURL,
					largeFile, itemFields, itemPrices, serviceContext);
			
			
			
			List<CustomField> list = (List) CustomFieldLocalServiceUtil.findByCategoryId(categoryId);
			
			for(CustomField field : list) {
				
				String fieldValue = ParamUtil.getString(uploadRequest, field.getKeyValue());
				CustomFieldValue cfValue = CustomFieldValueLocalServiceUtil.findByItemIdKeyvalue(itemId, field.getKeyValue());
				if(Validator.isNotNull(cfValue)) {
					cfValue.setRecId(cfValue.getRecId());
					cfValue.setItemId(item.getItemId());
					cfValue.setKeyName(field.getKeyValue());
					cfValue.setKeyValue(fieldValue);
					CustomFieldValueLocalServiceUtil.updateCustomFieldValue(cfValue);
				} else {
					cfValue = new CustomFieldValueImpl();
					long recId= CounterLocalServiceUtil.increment("CustomFieldValue.class");
					cfValue.setRecId(recId);
					cfValue.setKeyName(field.getKeyValue());
					cfValue.setKeyValue(fieldValue);
					cfValue.setItemId(item.getItemId());
					CustomFieldValueLocalServiceUtil.addCustomFieldValue(cfValue);
				}
				
				
				
			}

		}
	}
	
	
	public void updateCartlist(
			ActionRequest actionRequest, ActionResponse actionResponse)
		throws Exception {

		String cmd = ParamUtil.getString(actionRequest, Constants.CMD);

		ShoppingCart cart = ProductUtil.getCart(actionRequest);

		if (cmd.equals(Constants.ADD)) {
			long itemId = ParamUtil.getLong(actionRequest, "itemId");

			String fields = ParamUtil.getString(actionRequest, "fields");

			if (Validator.isNotNull(fields)) {
				fields = "|" + fields;
			}

			ShoppingItem item = ShoppingItemLocalServiceUtil.getItem(itemId);

			if (item.getMinQuantity() > 0) {
				for (int i = 0; i < item.getMinQuantity(); i++) {
					cart.addItemId(itemId, fields);
				}
			}
			else {
				cart.addItemId(itemId, fields);
			}
		}
		else {
			String itemIds = ParamUtil.getString(actionRequest, "itemIds");
			String couponCodes = ParamUtil.getString(
				actionRequest, "couponCodes");
			int altShipping = ParamUtil.getInteger(
				actionRequest, "altShipping");
			boolean insure = ParamUtil.getBoolean(actionRequest, "insure");

			cart.setItemIds(itemIds);
			cart.setCouponCodes(couponCodes);
			cart.setAltShipping(altShipping);
			cart.setInsure(insure);
		}

		ShoppingCartLocalServiceUtil.updateCart(
			cart.getUserId(), cart.getGroupId(), cart.getItemIds(),
			cart.getCouponCodes(), cart.getAltShipping(), cart.isInsure());

		if (cmd.equals(Constants.ADD) || cmd.equals(Constants.UPDATE)) {
			addSuccessMessage(actionRequest, actionResponse);
		}
		 
		 
	/*	String redirect = ParamUtil.getString(actionRequest, "redirect");

			String cartvalue="CartPage";
			PortletSession session = actionRequest.getPortletSession();
			session.setAttribute("sessionValue",cartvalue,PortletSession.APPLICATION_SCOPE);
			System.out.println("redirect"+redirect);
			actionResponse.setRenderParameter("jspPage","/html/portlet/shopping/view_item.jsp");*/
	
		
	}

}
